package com.project.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.LogBean;
import com.project.bean.SellBean;
import com.project.bean.SellOrderBean;
import com.project.mapper.ILogMapper;
import com.project.mapper.ISellOrderMapper;
import com.project.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class SellOrderService implements ISellOrderService {
    @Autowired
    private ISellOrderMapper sellOrderMapper;
    @Autowired
    private ISellService sellCarService;
    @Autowired
    private ISellDetailService sellDetailService;
    @Autowired
    private IGoodsService goodsService;

    @Override
    public IPage<SellOrderBean> findByItem(Integer pageNo, String customName, LocalDate startDate, LocalDate endDate) {
        QueryWrapper<SellOrderBean> qw = new QueryWrapper<>();
        if(customName!=null&&!customName.equals("")){
            qw.like("o_customName",customName);
        }
        if(startDate!=null){
            qw.ge("o_date",startDate);
        }
        if(endDate!=null){
            qw.le("o_date",endDate);
        }
        return sellOrderMapper.selectPage(new Page<>(pageNo,2),qw);
    }

    @Override
    public SellOrderBean findById(Integer sellOrderId) {
        SellOrderBean sellOrder = sellOrderMapper.selectById(sellOrderId);
        sellOrder.setSellDetailList(sellOrderMapper.findBySellOrderId(sellOrderId));
        return sellOrder;
    }

    @Override
    public void add(SellOrderBean sellOrder,Integer userId) {
        List<SellBean> sellCarList = sellCarService.findAll(userId);
        //添加订单
        sellOrderMapper.insert(sellOrder);
        //添加明细
        sellDetailService.add(sellOrder.getId(),sellCarList);
        //修改库存数量
        sellCarList.forEach(sellCarBean -> {
            goodsService.updateNum(sellCarBean.getGoodsBean().getId(),sellCarBean.getNum());
        });


    }
}